package com.app.web

import com.frame.utils.IpUtil

import com.google.code.kaptcha.Constants
import com.google.code.kaptcha.Producer

import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.apache.shiro.SecurityUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

import javax.imageio.ImageIO
import javax.servlet.ServletOutputStream
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.core.Context
import javax.ws.rs.core.MediaType
import java.awt.image.BufferedImage

/**
 * Created with IntelliJ IDEA.
 * com.chengheng.fps.manage.web
 * User: 张斌
 * Date: 2014/5/16
 */

@Component
@CompileStatic
@TypeChecked
@Path("/")
class ValidCodeAction {


    @Autowired(required = false)
    private Producer captchaProducer

    /**
     * 验证码图片
     * @author 张斌
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Path("vaildCode.jpg")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String validCode(@Context HttpServletRequest request,@Context HttpServletResponse response) throws Exception{

        response.setDateHeader("Expires", 0)
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate")
        response.addHeader("Cache-Control", "post-check=0, pre-check=0")
        response.setHeader("Pragma", "no-cache")
        response.setHeader("Access-Control-Allow-Origin","*")
        response.setContentType("image/jpeg")
        String capText = captchaProducer.createText()
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        request.getSession().id;
        // SecurityUtils.getSubject().getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,capText);
        //获取请求IP放入session
        request.getSession().setAttribute("reqIp", IpUtil.getIpAddr(request))
        BufferedImage bi = captchaProducer.createImage(capText)
        ServletOutputStream out = response.getOutputStream()
        ImageIO.write(bi, "jpg", out)
        try {
            out.flush()
        } finally {
            out.close()
        }
        return null
    }
}
